const { defineComponent: Component } = require('san/san')

const Skeleton = Component({
    template: `
        <template>
            <div s-if="show" class="san-skeleton">
                <div class="skeleton-box">
                    <template s-for="item in list">
                        <div class="skeleton-line">
                            <template s-for="v in item">
                                <div class="skeleton-item" style="width: {{v}}%"></div>
                            </template>
                        </div>
                    </template>
                </div>
            </div>
        </template>
    `,
    inited () {
        this.watch('show', v => {
            const $parent = $(this.el).parent()
            if (!v) {
                let position = this.data.get('position')
                if (!position) return
                $parent.css('position', position)
            } else {
                this.data.set('position', 'relative')
                $parent.css('position', 'relative')
            }
        })
    },
    attached() {
        let $el = $(this.el)
        let $parent = $el.parent()
        let position = $parent.css('position')
        this.data.set('position', position)
        $parent.css('position', 'relative')

        this.nextTick(() => {
            const height = parseInt($parent.css('height')) + 4
            let ctnHeight = height - 48
            let count = Math.round(ctnHeight / 32)
            let arr = []
            for (let i = 0; i < count; i++) {
                let tmpData = this.data.get('tmpData')
                let index = Math.floor((Math.random() * tmpData.length))
                arr.push(tmpData[index])
            }
            this.data.set('list', arr, { force: true })
        })
    },
    initData () {
        return {
            position: '',
            tmpData: [[88], [65, 27], [28, 60], [12, 52 ,24]],
        }
    }
})

module.exports = Skeleton